package mrms.api.web;

import lombok.extern.slf4j.Slf4j;
import mrms.api.web.authentication.AuthenticationException;
import mrms.api.web.utils.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedList;
import java.util.List;

/**
 * @author lenchu
 * @date 2019/01/31
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage(), e);
    }

    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException e) {
        List<String> errors = new LinkedList<>();
        for (String ex : e.getErrors()) {
            errors.add(ex);
            log.error(ex);
        }
        return Result.error(errors.get(errors.size() - 1), errors);
    }
}
